const { default: axios } = require('axios');
const express = require('express');
const { getSwiperList, getNewsList, getNewsInfo, getImageList } = require('../services');

const router = express.Router();

router.get('/', function (req, resp) {
	resp.json({ code: 200, message: '测试' });
});

// 获取轮播图数据
router.get('/swiper', (req, resp) => {
	getSwiperList().then(swipers => resp.json({ code: 200, swipers }));
});

// 获取新闻数据
router.get('/newslist/:page', (req, resp) => {
	getNewsList(parseInt(req.params.page))
		.then(data => resp.json(data))
		.catch(err => {
			console.error('获取新闻列表失败', err.message);
			resp.json({ code: 500 });
		});
});

// 获取新闻详情
router.get('/newsinfo/:type/:id', (req, resp) => {
	getNewsInfo(req.params.type, req.params.id)
		.then(data => resp.json(data))
		.catch(err => {
			console.error('获取新闻详情失败', err.message);
			resp.json({ code: 500 });
		});
});

// 获取缩略图
router.get('/imagelist/:id', (req, resp) => {
	getImageList(req.params.id)
		.then(data => resp.json(data))
		.catch(err => {
			console.error('获取缩略图失败', err.message);
			resp.json({ code: 500 });
		});
});

router.get('/test', function(req, resp) {
	axios.get('https://bbs.zdfx.net/forum-2-1.html')
		.then(function(data) {
			resp.send(data.data);
		})
		.catch(function() {
			resp.json({ code: 500, message: '请求出错' });
		});
});

// 404
router.get('*', (req, resp) => {
	resp.json({ code: 404, message: 'Not Found' });
});

module.exports = router;
